<?php
header("Content-type:text/html; charset=utf-8;");
require '../../../ppf/fun.php';
require '../../../ppf/pdo_mysql.php';
require '../../../ppf/Filter.php';
date_default_timezone_set("PRC");
$pd=new pdo_mysql();
$filter=new Filter();
session_start();
if(empty($_SESSION['uid'])){
	echo '请登录后再进行操作';exit;
}
$submitMethod=$_SERVER["REQUEST_METHOD"];
if($submitMethod=='POST'){
	$id = empty($_POST['id'])?"":$_POST['id'];
    $now=date('Y-m-d H:i:s',time());
    $name = empty($_POST['name'])?"":$_POST['name'];
    $content = empty($_POST['content'])?"":$_POST['content'];
	$type = empty($_POST['type'])?1:$_POST['type'];
	$start_time = empty($_POST['start_time'])?date('Y-m-d',time()):$_POST['start_time'];//开始时间为空即为立即生效
	$end_time = empty($_POST['end_time'])?"":$_POST['end_time'];//结束时间为空即为手动终止
	$dept_id   = empty($_POST['dept_id'])?'':Filter::filter_html($_POST['dept_id']);
	$accept_id   = empty($_POST['accept_id'])?'':Filter::filter_html($_POST['accept_id']);
	$charge_id   = empty($_POST['charge_id'])?'':Filter::filter_html($_POST['charge_id']);
	$remark   = empty($_POST['remark'])?"":$_POST['remark'];
	$attachment='';
    if($_POST['attachment']!=''){
    	$attachment_info=json_decode($_POST['attachment']);
		$attach=array();
    	foreach($attachment_info as $k=>$v){
			$attach[]=array('id'=>Filter::safe_string($v->id),'name'=>Filter::safe_string($v->name),'save_path'=>Filter::safe_string($v->save_path),'timestamp'=>time());
    		$attachment.=Filter::safe_string($v->id).',';
    	}
    }
	$attachment=rtrim($attachment,",");
	if(!$id){
		$rs = $pd->exec("insert into sys_plan(uid,name,content,time,type,start_time,end_time,dept_id,accepter,charge_uid,remark,attachment) values(
											'".$_SESSION['uid']."',
											'".$name."',
											'".$content."',
											'".$now."',
											'".$type."',
											'".$start_time."',
											'".$end_time."',
											'".$dept_id."',
											'".$accept_id."',
											'".$charge_id."',
											'".$remark."',
											'".$attachment."'
			)");
		if($rs){
			if(isset($attach)){
				foreach($attach as $k=>$v){
					$pd->insert(array('data'=>$v,'table'=>'sys_plan_attachment'));
				}
			}
			$tips='新建工作计划成功';
		}else{
			$tips='新建工作计划失败，请重试';
		}
		echo $tips;exit;
	}else{
		$rs = $pd->exec("update sys_plan set 
			name='".$name."',
			content='".$content."',
			time='".$now."',
			type='".$type."',
			start_time='".$start_time."',
			end_time='".$end_time."',
			dept_id='".$dept_id."',
			accepter='".$accept_id."',
			charge_uid='".$charge_id."',
			remark='".$remark."',
			attachment='".$attachment."' where id=".$id);
		if($rs){
			if(isset($attach)){
				foreach($attach as $k=>$v){
					$pd->insert(array('data'=>$v,'table'=>'sys_plan_attachment'));
				}
			}
			$tips='更新工作计划成功';
		}else{
			$tips='更新工作计划失败，请重试';
		}
		echo $tips;exit;
	}
	
}else{
	echo '不允许的表单提交方式，请按正常流程提交表单。';exit;
}
?>